<template>
  <div class="wrapper">
    <div class="menu">
      <ul>
        <li
          v-for="tab in tabs"
          :key="tab.title"
          class="tab"
          :class="{ active: activeTab === tab.title }"
          @click="switchTab(tab.title)"
        >
          {{ tab.title }}
        </li>
      </ul>
    </div>
    <div class="content">
      <div
        v-for="tab in tabs"
        :key="tab.title"
        class="item"
        :class="{ selected: activeTab === tab.title }"
        v-show="activeTab === tab.title"
      >
        {{ tab.content }}
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';

const activeTab = ref('');
const selectedContent = ref('');
const tabs = ref([]);

// 初始化状态
const isSwitch = async () => {
  const result = await axios.get('http://localhost:4000/tab');
  activeTab.value = result.data.activeTab;
  selectedContent.value = result.data.selectedContent;
  tabs.value = result.data.tabs;
};

// 挂载时初始化状态
onMounted(isSwitch);

// 切换选项卡
const switchTab = async (newTab) => {
  const result = await axios.post('http://localhost:4000/tabs', { tab: newTab });
  activeTab.value = result.data.activeTab;
  selectedContent.value = result.data.selectedContent;
};
</script>

<style>
* {
  padding: 0;
  margin: 0;
}

.wrapper {
  width: 600px;
  height: 300px;
  border: 1px solid skyblue;
  margin: 50px auto;
}

.menu .tab {
  list-style-type: none;
  float: left;
  cursor: pointer;
  width: 200px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #87ceeb;
  box-sizing: border-box;
}

.menu .tab.active {
  background-color: pink;
}

.content .item {
  padding: 20px;
  display: none;
  text-indent: 20px;
  word-wrap: break-word;
}

.content .item.selected {
  display: block;
}
</style>
